import { ApiResponse } from '@/types';

export const mentors = [
  {
    id: 'sheldon',
    name: '谢耳朵',
    avatar: '/images/sheldon.png',
    quote: 'Bazinga!',
  },
  {
    id: 'confucius',
    name: '孔子',
    avatar: '/images/confucius.png',
    quote: '三人行，必有我师焉',
  },
  {
    id: 'guo',
    name: '郭德纲',
    avatar: '/images/guo.png',
    quote: '嘛钱不钱的，乐呵乐呵得了',
  }
];

export async function getEncouragement(mentorId: string, userInput: string): Promise<ApiResponse> {
  try {
    console.log('发送API请求...', { mentorId, userInput: userInput.substring(0, 50) });

    const response = await fetch('/api/encourage', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        mentorId,
        userInput
      }),
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
    }

    const data = await response.json();

    if (!data.success) {
      throw new Error(data.error || 'API调用失败');
    }

    console.log('API调用成功');

    return {
      reply: data.reply
    };

  } catch (error) {
    console.error('API调用失败:', error);

    let errorMessage = '抱歉，网络出现问题，请稍后再试。';

    if (error instanceof Error) {
      if (error.message.includes('API key')) {
        errorMessage = 'API密钥配置错误，请检查配置。';
      } else if (error.message.includes('quota')) {
        errorMessage = 'API调用次数已达上限，请稍后再试。';
      } else if (error.message.includes('network') || error.message.includes('fetch')) {
        errorMessage = '网络连接失败，请检查网络设置。';
      } else {
        errorMessage = `API调用失败: ${error.message}`;
      }
    }

    return {
      reply: errorMessage
    };
  }
}